import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {baseHandleError, ReturnForm, ReturnPage} from '@sb/base';
import {HttpClient} from '@angular/common/http';
import {environment} from '../../../../environments/environment';
import {DcFeature} from '../entity/dc-feature';
import {catchError, tap} from 'rxjs/operators';
import {Extent} from 'ol/extent';
import {DcVectorLayerQueryOptions} from '../entity/dc-vector-layer-query-options';
import {NzMessageService} from 'ng-zorro-antd';
import Feature from 'ol/Feature';

@Injectable({
    providedIn: 'root'
})
export class DcVectorLayerOperateService {

    private url = `${environment.baseServerUrl}/layer/operate`;

    constructor(private httpClient: HttpClient,
                private message: NzMessageService) {
    }

    /**
     * @param layerId 图层ID
     * @param keyId 主键
     */
    get(layerId: string, keyId: string): Observable<ReturnForm<DcFeature>> {
        return this.httpClient.get<ReturnForm<DcFeature>>(`${this.url}/${layerId}/get/${keyId}`).pipe(
            catchError(baseHandleError<ReturnForm<DcFeature>>('get'))
        );
    }

    /**
     * 按范围进行查询
     * @param layerId 图层标识
     * @param extent 范围
     */
    queryByExtentOnly(layerId, extent: Extent): Observable<ReturnForm<DcFeature[]>> {
        return new Observable<ReturnForm<DcFeature[]>>(subscriber => {
            this.query(layerId, {
                geometry: `POLYGON ((${extent[0]} ${extent[1]}, ${extent[2]} ${extent[1]}, ${extent[2]} ${extent[3]}, ${extent[0]} ${extent[3]}, ${extent[0]} ${extent[1]}))`,
                returnGeometry: true,
                searchCount: false
            }).subscribe(value => {
                if (value.success) {
                    subscriber.next({
                        success: true,
                        message: value.message.rows
                    });
                }

            });
        });
    }

    query(layerId, queryOptions: DcVectorLayerQueryOptions): Observable<ReturnForm<ReturnPage<DcFeature>>> {

        return this.httpClient.post<ReturnForm<ReturnPage<DcFeature>>>(`${this.url}/${layerId}/queryWithPage`, queryOptions, {
            headers: {
                'Content-Type': 'application/json;ChartSet=UTF-8'
            }
        }).pipe(
            tap(v => {
                if (v.success === false) {
                    this.message.info('数据查询出错');
                }
            }),
            catchError(baseHandleError<ReturnForm<ReturnPage<DcFeature>>>('queryWithPage'))
        );

        //
        // //封装查询参数
        // param = changeToVectorParam(param);
        // var count = $SbMainMapParam.getCount(param.dataSetId);
        // //数据量大于 1000 条时开启web socket
        // if (count > 1000 && typeof WebSocket != 'undefined') {
        //     //支持web socket
        //     //创建长连接， 分量查询数据
        //
        //     var protrol = "ws:";
        //     if (window.location.protocol === 'https:') {
        //         protrol = "wss:";
        //     }
        //     // var ws = new WebSocket(protrol + "//" + window.location.host + "/dataQuery/ws");
        //     var ws = new WebSocket(protrol + "//" + dcServerHost + "/dataQuery/ws");
        //     ws.onclose = function (ev) {
        //     };
        //     ws.onmessage = function (ev) {
        //         var result = JSON.parse(ev.data);
        //         var total = result.total;
        //         var page = result.page;
        //         var data = result.data;
        //         var olFeatures = changeToFeature(param.dataSetId, data);
        //         if (callback) {
        //             var c = callback({
        //                 total: total,
        //                 page: page,
        //                 features: olFeatures
        //             });
        //             if (c === true) {
        //                 ws.close();
        //             }
        //         }
        //     };
        //     ws.onopen = function (ev) {
        //         var ms = {begin: true, data: param};
        //         ms = JSON.stringify(ms);
        //         ws.send(ms);
        //     }
        // } else {
        // 不支持web socket 或 数据量小于10000条
        // 同步调用，获得承诺接口

        // }
    }

    /**
     * @param param 查询参数
     *
     *       projectLayerId * 专题Id
     *       queryGeometry  查询空间
     *       queryValue 模糊搜索
     *       queryParam 属性查询，按字段查询
     *       pageParam {
     *           orderField 排序字段
     *           orderType  排序类型
     *           startRow 开始条目 default 1
     *           endRow  结束条目  default 999999999999999999
     *       }
     *       returnFields  返回字段信息
     *       returnTotal 是否返回总数
     *
     * @returns object
     *       {
     *           total default 0
     *           features  [ol.Feature]
     *       }
     */
    exportExcel(param) {
        alert('暂未提供此功能');
    }

    // private updateParam(param: DcVectorLayerQueryOptions): DcVectorLayerQueryOptions {
    //     if (param.geometry && param.geometry instanceof Geometry) {
    //         param.geometry = this.wktFormat.writeGeometry(param.geometry);
    //     }
    //     return param;
    // }

    private changeToFeature(dcFeatures: DcFeature[]): Feature[] {
        return [];
    }
}
